import 'package:edu/constants/app_strings.dart';
import 'package:edu/pages/signin/verify_code_submit/verify_code_submit_page_logic.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:provider/provider.dart';

class VerifyCodeSubmitPage extends StatefulWidget {
  const VerifyCodeSubmitPage({super.key});

  @override
  State<VerifyCodeSubmitPage> createState() => _VerifyCodeSubmitPageState();
}

class _VerifyCodeSubmitPageState extends State<VerifyCodeSubmitPage> {
  @override
  void initState() {
    super.initState();
    context.read<VerifyCodeSubmitPageLogic>().init();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(context),
      body: _buildMainBody(context),
    );
  }

  Widget _buildMainBody(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(height: 20),
          const Text(AppStrings.inputVerifyCode),
          const SizedBox(height: 10),
          _buildPasswordInputWidget(context),
          const SizedBox(height: 20),
          _buildPinCodeInput(context),
          const SizedBox(height: 30),
          _buildMainButtonRow(context),
        ],
      ),
    );
  }

  Widget _buildMainButtonRow(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      height: 44,
      child: Selector<VerifyCodeSubmitPageLogic, bool>(
        selector: (context, logic) => logic.canSubmit,
        builder: (context, v, child) {
          return ElevatedButton(
            onPressed: v ? _mainButtonPressed : null,
            style: ButtonStyle(
              shape: WidgetStateProperty.all<RoundedRectangleBorder>(
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
              ),
            ),
            child: Text(
              AppStrings.submit,
              style: Theme.of(context).textTheme.titleMedium,
            ),
          );
        },
      ),
    );
  }

  // 密码输入框
  Widget _buildPasswordInputWidget(BuildContext context) {
    final logic = context.read<VerifyCodeSubmitPageLogic>();
    if (logic.submitType == VerifyCodeSubmitPageLogic.kResetPassword) {
      return Column(
        children: [
          Selector<VerifyCodeSubmitPageLogic, bool?>(
            selector: (context, logic) => logic.password1Ready,
            builder: (context, v, child) {
              final primaryColor = Theme.of(context).colorScheme.primary;
              final Widget? suffixIcon;
              if (v != null) {
                suffixIcon = Icon(
                  v ? Icons.check : Icons.error,
                  color: v ? primaryColor : Colors.red,
                );
              } else {
                suffixIcon = null;
              }
              return TextField(
                obscureText: true,
                autofocus: true,
                controller: logic.passwordController1,
                focusNode: logic.focusNode1,
                maxLength: 20,
                buildCounter:
                    (
                      context, {
                      required currentLength,
                      required isFocused,
                      maxLength,
                    }) {
                      return null;
                    },
                decoration: InputDecoration(
                  labelText: AppStrings.newPassword,
                  hintText: AppStrings.inputNewPassword,
                  suffixIcon: suffixIcon,
                ),
              );
            },
          ),
          const SizedBox(height: 10),
          Selector<VerifyCodeSubmitPageLogic, bool?>(
            selector: (context, logic) => logic.password2Ready,
            builder: (context, v, child) {
              final primaryColor = Theme.of(context).colorScheme.primary;
              final Widget? suffixIcon;
              if (v != null) {
                suffixIcon = Icon(
                  v ? Icons.check : Icons.error,
                  color: v ? primaryColor : Colors.red,
                );
              } else {
                suffixIcon = null;
              }
              return TextField(
                obscureText: true,
                controller: logic.passwordController2,
                focusNode: logic.focusNode2,
                maxLength: 20,
                buildCounter:
                    (
                      context, {
                      required currentLength,
                      required isFocused,
                      maxLength,
                    }) {
                      return null;
                    },
                decoration: InputDecoration(
                  labelText: AppStrings.confirmPassword,
                  hintText: AppStrings.inputConfirmPassword,
                  suffixIcon: suffixIcon,
                ),
              );
            },
          ),
        ],
      );
    } else {
      return const SizedBox.shrink();
    }
  }

  void _mainButtonPressed() {
    final logic = context.read<VerifyCodeSubmitPageLogic>();
    logic.submit().then((value) {
      if (value) {
        if (logic.prevRoute != null) {
          Navigator.of(
            context,
          ).popUntil((route) => route.settings.name == logic.prevRoute);
        } else {
          Navigator.of(context).pop();
        }
      }
    });
  }

  // 输入框
  Widget _buildPinCodeInput(BuildContext context) {
    final logic = context.watch<VerifyCodeSubmitPageLogic>();
    final fillColor = Theme.of(context).colorScheme.surface;
    final activeColor = Theme.of(context).colorScheme.primary;
    return PinCodeTextField(
      appContext: context, // 上下文
      length: 6,
      obscureText: false, // 是否隐藏输入
      animationType: AnimationType.fade, // 输入框动画
      textCapitalization: TextCapitalization.characters, // 大写
      inputFormatters: [
        FilteringTextInputFormatter.allow(RegExp(r'[A-Z0-9]')),
      ], // 输入框格式
      keyboardType: TextInputType.text, // 键盘类型
      controller: logic.textController, // 控制器
      focusNode: logic.focusNode, // 焦点
      // 输入框样式
      pinTheme: PinTheme(
        shape: PinCodeFieldShape.box,
        borderRadius: BorderRadius.circular(5), // 边框圆角
        fieldHeight: 50, // 字体大小
        fieldWidth: 40, // 字体大小
        activeFillColor: fillColor, // 激活填充颜色
        inactiveFillColor: fillColor.withAlpha(128), // 未激活填充颜色
        inactiveColor: Colors.grey, // 未激活边框颜色
        activeColor: activeColor, // 激活边框颜色
        selectedFillColor: fillColor, // 激活填充颜色
        selectedColor: activeColor, // 激活边框颜色
      ),
    );
  }

  AppBar _buildAppBar(BuildContext context) {
    final logic = context.watch<VerifyCodeSubmitPageLogic>();
    return AppBar(title: Text(logic.title));
  }
}
